<template>
  <div class="AllBox">
    <div class="fixedBox">
      <div class="typeTitle" @click="handelEdit">数据统计</div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="客户名称">
          <el-input v-model="searchText" placeholder="请输入客户名称" suffix-icon="el-icon-search"></el-input>
        </el-form-item>
        <el-form-item label="服务时间">
          <el-input v-model="searchText2" placeholder="请输入服务时间" suffix-icon="el-icon-search"></el-input>
        </el-form-item>
      </el-form>
      <div class="typeTitle" style="background: linear-gradient(to right, #F5D8CB 0%, #CECCCD 100%);">
        检索情况
      </div>

      <el-table :data="tabledate" border style="margin-top:20px;" header-cell-style="color:#535456;">
        <el-table-column label="主体">
          <template #default="scope">
            <el-input v-model="scope.row.a" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.a }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用平台">
          <template #default="scope">
            <el-input v-model="scope.row.b" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.b }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布内容">
          <template #default="scope">
            <el-input v-model="scope.row.c" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.c }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务时间" prop="d">
          <template #default="scope">
            <el-input v-model="scope.row.d" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.d }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总时长" prop="e">
          <template #default="scope">
            <el-input v-model="scope.row.e" v-if="isEdit"></el-input>
            <span style="color:#11660B;font-weight:700;" v-else>{{ scope.row.e }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击量" prop="f">
          <template #default="scope">
            <el-input v-model="scope.row.f" v-if="isEdit"></el-input>
            <span style="color:#F15B26;font-weight:700;" v-else>{{ scope.row.f }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="g">
          <template #default="scope">
            <span style="color:#448CD6;font-weight:700;">{{ scope.row.g }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="padding:10px 0;">
      <el-button type="primary" @click="importExcel" v-if="isEdit">导入Excel</el-button>
      <input type="file" ref="fileInput" @change="handleFileUpload" style="display: none;" accept=".xlsx, .xls"/>
      <!-- <div ref="chartContainer" style="width: 100%; height: 400px;"></div> -->
      <!-- 动态表格 -->
      <el-table :data="paginatedTableData" border style="margin-top:20px;"  header-cell-style="color:#535456; text-align: center;" :row-class-name="tableRowClassName" max-height="520">
        <el-table-column label="广告标题" prop="title">
          <template #default="scope">
            <el-input v-model="scope.row.title" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="投放日期" prop="date" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.date" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.date }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时间" prop="time" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.time" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="展示量" prop="impressions" width="128">
          <template #default="scope">
            <el-input v-model="scope.row.impressions" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.impressions }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击数" prop="clicks" width="128">
          <template #default="scope">
            <el-input v-model="scope.row.clicks" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.clicks }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击率" prop="ctr" width="128">
          <template #default="scope">
            <el-input v-model="scope.row.ctr" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.ctr }}</span>
          </template>
        </el-table-column>
        <el-table-column label="阅读平均时效" prop="avgReadTime" width="128">
          <template #default="scope">
            <el-input v-model="scope.row.avgReadTime" v-if="isEdit"></el-input>
            <span v-else>{{ scope.row.avgReadTime }}</span>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
      style="margin-top: 0px;"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10,20, 40, 60, 80]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length">
      </el-pagination>
      <!-- <div ref="chartContainer" style="width: 100%; height: 400px;"></div> -->
      <div>
        <!-- <h1>{{  '综合数据' }}</h1> -->
        <div v-if="!isEdit" ref="chartContainer" style="width: 100%; height: 400px;"></div>
      </div>
    </div>
  </div>
</template>

<script lang='ts' setup>
import { ref, onMounted, watchEffect, computed } from 'vue';
import { ElMessageBox, ElMessage } from "element-plus";
import * as XLSX from 'xlsx';
import * as echarts from 'echarts';

const chartData = computed(() => {
  return {
    dates: tableData.value.map(item => item.date),
    impressions: tableData.value.map(item => parseInt(item.impressions)),
    clicks: tableData.value.map(item => parseInt(item.clicks)),
    clickRate: tableData.value.map(item => parseFloat(item.ctr)),  // 直接使用 parseFloat
    readingTime: tableData.value.map(item => parseFloat(item.avgReadTime)) 
  };
});

function parseTimeToSeconds(timeStr) {
  const [minutes, seconds] = timeStr.split(':').map(Number);
  return minutes * 60 + seconds;
}

const isEdit = ref(false);
const searchText = ref("");
const searchText2 = ref("");
const tabledate = ref([{
  a: '中华财险西安中心支公司',
  b: '网页推广',
  c: '车险',
  d: '2024/4/1-2024/4/12',
  e: '162h',
  f: '49,102',
  g: '正常',
},]);
const tabledate1 = ref([{
  a: '7,481',
  b: '7,336',
  c: '+15.8%',
  d: '5.2%',
  e: '00:01:20',
},]);
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);

const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const importExcel = () => {
  fileInput.value.click();
};

const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      const headers = jsonData[0];
      const rows = jsonData.slice(1);

      // 过滤掉空行和无效行
      const filteredRows = rows.filter(row => row.every(cell => cell !== undefined && cell !== null && cell !== ''));

      const formattedData = filteredRows.map(row => {
        const ctrValue = row[headers.indexOf('点击率')];
       const ctrPercentage = (ctrValue * 100).toFixed(2) + '%';  // 将 ctr 转换为百分比字符串

        const avgReadTimeValue = row[headers.indexOf('阅读平均时效')];
        const avgReadTime2 = avgReadTimeValue

        const dateValue = row[headers.indexOf('投放日期')];
        let dateStr = '';
        if (typeof dateValue === 'number') {
          // 处理 Excel 日期格式
          dateStr = XLSX.SSF.format('yyyy/mm/dd', dateValue);
        } else if (typeof dateValue === 'string') {
          dateStr = dateValue;
        }

        return {
          title: row[headers.indexOf('广告标题')],
          date: dateStr,
          time: row[headers.indexOf('时间')],
          impressions: row[headers.indexOf('展示量')],
          clicks: row[headers.indexOf('点击数')],
          ctr: ctrPercentage,
          avgReadTime: avgReadTime2
        };
      });
     // 去掉 formattedData 中标题为空的数据
     const cleanedData = formattedData.filter(item => item.title !== undefined && item.title !== null && item.title !== '');
tableData.value = cleanedData;
    };
    reader.readAsArrayBuffer(file);
  }
};

const fileInput = ref(null);

const handelEdit = function () {
  isEdit.value = !isEdit.value;
};

const tableRowClassName = ({ rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return 'even-row';
  } else {
    return 'odd-row';
  }
};

const chartContainer = ref(null);

onMounted(() => {
  tableData.value = [
    { title: '广告1', date: '2024-04-01', time: '10:00', impressions: '1000', clicks: '50', ctr: '5%', avgReadTime: '40s' },
    { title: '广告2', date: '2024-04-02', time: '11:00', impressions: '1500', clicks: '75', ctr: '5%', avgReadTime: '35s' },
    // 更多数据...
  ];

  // 确保 chartContainer 存在后再初始化 ECharts
  if (chartContainer.value) {
    const chart = echarts.init(chartContainer.value);
    const option = {
      color: ['#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00'],
      title: {
        text: '综合数据图表'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      legend: {
        data: ['展示量', '点击数', '点击率', '阅读平均时效']
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: chartData.value.dates
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '数量',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#80FFA5'
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '百分比',
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#00DDFF'
            }
          },
          axisLabel: {
            formatter: '{value}%'
          }
        },
        {
          type: 'value',
          name: '秒',
          position: 'right',
          offset: 80,
          axisLine: {
            lineStyle: {
              color: '#37A2FF'
            }
          },
          axisLabel: {
            formatter: '{value}s'
          }
        }
      ],
      series: [
        {
          name: '展示量',
          type: 'bar',
          yAxisIndex: 0,
          data: chartData.value.impressions
        },
        {
          name: '点击数',
          type: 'bar',
          yAxisIndex: 0,
          data: chartData.value.clicks
        },
        {
          name: '点击率',
          type: 'line',
          yAxisIndex: 1,
          data: chartData.value.clickRate
        },
        {
          name: '阅读平均时效',
          type: 'line',
          yAxisIndex: 2,
          data: chartData.value.readingTime
        }
      ]
    };
    chart.setOption(option);
  }
});

watchEffect(() => {
  if (chartContainer.value && chartData.value.dates.length > 0) {
    const chart = echarts.init(chartContainer.value);
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        }
      },
      legend: {
        data: ['展示量', '点击数', '点击率', '阅读平均时效']
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          boundaryGap: false,
          data: chartData.value.dates
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '数量',
          position: 'left',
          axisLine: {
            lineStyle: {
              color: '#80FFA5'
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '百分比',
          position: 'right',
          axisLine: {
            lineStyle: {
              color: '#00DDFF'
            }
          },
          axisLabel: {
            formatter: '{value}%'
          }
        },
        {
          type: 'value',
          name: '秒',
          position: 'right',
          offset: 80,
          axisLine: {
            lineStyle: {
              color: '#37A2FF'
            }
          },
          axisLabel: {
            formatter: '{value}s'
          }
        }
      ],
      series: [
        {
          name: '展示量',
          type: 'bar',
          yAxisIndex: 0,
          data: chartData.value.impressions
        },
        {
          name: '点击数',
          type: 'bar',
          yAxisIndex: 0,
          data: chartData.value.clicks
        },
        {
          name: '点击率',
          type: 'line',
          yAxisIndex: 1,
          data: chartData.value.clickRate
        },
        {
          name: '阅读平均时效',
          type: 'line',
          yAxisIndex: 2,
          data: chartData.value.readingTime
        }
      ]
    };
    chart.setOption(option);
  }
});
</script>
<style lang='css' scoped>
.AllBox{
  position: relative;
}
.fixedBox{
  /* 吸顶到AllBox */
  position: sticky;
  top: 0;
  z-index: 99;
  background-color: #ECF3FB;
 

}
.typeTitle {
  cursor: pointer;
  padding: 10px 10px;
  font-size: 18px;
}

.el-breadcrumb {
  margin-bottom: 14px;
}

/deep/ .el-table .even-row {
  background-color: #FFFFFF;
}

/deep/ .el-table .odd-row {
  background-color: #F9F9F9;
}

/deep/ .el-table .cell {
  text-align: center;
}

</style>